package com.learn.smart.framework.helper;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.learn.smart.framework.annotation.RequestMapping;
import com.learn.smart.framework.bean.Handler;
import com.learn.smart.framework.bean.Request;

public class ControllerHelper {
	
	private static final Map<Request,Handler> ACTION_MAP = new HashMap<Request, Handler>();
	
	static{
		Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();
		for(Class<?> controllerClass : controllerClassSet){
			Method[] methods = controllerClass.getDeclaredMethods();
			if(methods!=null&&methods.length>0){
				for(Method method : methods){
					if(method.isAnnotationPresent(RequestMapping.class)){
						RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
						String mapping = requestMapping.value();
						if(mapping.matches("\\w+:/\\w*")){
							String[] array = mapping.split(":");
							if(mapping!=null&&mapping.length()>0){
								String requestMethod = array[0];
								String requestPath = array[1];
								Request request = new Request(requestMethod,requestPath);
								Handler handler = new Handler(controllerClass,method);
								ACTION_MAP.put(request, handler);
							}
						}
					}
				}
			}
		}
	}
	
	public static void init(){
		System.out.println("Controller请求配置");
	}
	
	public static Handler getHandler(String requestMethod,String requestPath){
		Request request = new Request(requestMethod,requestPath);
		return ACTION_MAP.get(request);
	}

}
